package com.google.code.mircle.core.transfers;

import java.io.EOFException;
import java.io.File;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

import org.apache.commons.io.FileUtils;

import com.google.code.mircle.core.Core;
import com.google.code.mircle.core.Model;
import com.google.code.mircle.core.Plugin;
import com.google.code.mircle.core.Root;
import com.google.code.mircle.core.View;
import com.thoughtworks.xstream.XStream;

public class TransfersPlugin implements Plugin, Model, Root {

    File downloadFolder;
    Core core;
    DirectModel direct;
    Model[] models;

    public TransfersPlugin(Core core) {
        this.core = core;

        direct = new DirectModel(core, this);
        models = new Model[] { direct, new QueueModel("Queue") };

        downloadFolder = new File("/Users/axet/Downloads");
    }

    public void close() {
        for (Model m : getModels()) {
            m.close();
        }
    }

    public String getName() {
        return "Transfers";
    }

    public Model[] getModels() {
        return models;
    }

    public DirectModel getDirect() {
        return direct;
    }

    public JPopupMenu contextMenu(Model m) {
        JPopupMenu popup = new JPopupMenu();
        popup.add(new JMenuItem("123"));
        return popup;
    }

    public View createView(Model m) {
        if (m instanceof DirectModel)
            return new DirectView(core, (DirectModel) m, this);
        if (m instanceof QueueModel)
            return new QueueView((QueueModel) m);
        if (m instanceof TransfersPlugin)
            return new TransfersSettingsView((TransfersPlugin) m);
        return null;
    }

    @Override
    public void save(File path) {
        try {
            XStream stream = xstream();
            String xml = stream.toXML(direct.save());
            core.save(xml, FileUtils.getFile(path, "direct.xml"));
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    XStream xstream() {
        XStream stream = new XStream();
        stream.processAnnotations(new Class[] { DirectDownload.State.class, VGetDownload.State.class,
                EchoRuDownload.class });
        return stream;
    }

    @Override
    public void load(File path) {
        try {
            XStream s = xstream();
            Object state = s.fromXML(FileUtils.getFile(path, "direct.xml"));
            direct.load(state);
        } catch (com.thoughtworks.xstream.io.StreamException stream) {
            try {
                throw stream.getCause();
            } catch (EOFException ignore) {
                // empty file
            } catch (Throwable e) {
                throw new com.thoughtworks.xstream.io.StreamException(e);
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
